package datastructure_algorithm.array;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SparseArray {

	public static void main(String[] args) {
		// chess board 11 * 11
		// 1 is black
		// 2 is white
		int row = 11;
		int col = 11;
		int[][] arr = new int[row][col];
		arr[1][2] = 1;
		arr[2][3] = 2;
		arr[4][5] = 2;
		printBoard(arr);

		int[][] sparseArray = convertToSparseArray(arr);
		System.out.println("=====================");
		for (int i = 0; i < sparseArray.length; i++) {
			System.out.printf("%d\t%d\t%d\n", sparseArray[i][0], sparseArray[i][1], sparseArray[i][2]);
		}

		saveArray(sparseArray, "game2.data");
		saveArray(sparseArray, "game.data");

		System.out.println("=====================");
		int[][] arr2 = reconverteToArray(sparseArray);

		printBoard(arr2);
	}

	private static void saveArray(int[][] arr, String filename) {
		try (var out = new ObjectOutputStream(new FileOutputStream(filename))) {
			out.writeObject(arr);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static int[][] reconverteToArray(int[][] sparseArray) {
		int[][] arr2 = new int[sparseArray[0][0]][sparseArray[0][1]];
		for (int i = 1; i < sparseArray.length; i++) {
			int r = sparseArray[i][0];
			int c = sparseArray[i][1];
			int v = sparseArray[i][2];
			arr2[r][c] = v;
		}
		return arr2;
	}

	private static int[][] convertToSparseArray(int[][] arr) {
		int row = arr.length;
		int col = arr[0].length;
		int elements = 0;
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				int v = arr[i][j];
				if (v != 0) {
					elements++;
				}
			}
		}

		int[][] sarr = new int[elements + 1][3];
		sarr[0][0] = row;
		sarr[0][1] = col;
		sarr[0][2] = elements;
		int sarrRow = 1;

		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				int v = arr[i][j];
				if (v != 0) {
					sarr[sarrRow][0] = i;
					sarr[sarrRow][1] = j;
					sarr[sarrRow][2] = v;
					sarrRow++;
				}
			}
		}
		return sarr;
	}

	private static void printBoard(int[][] arr) {
		for (int[] row : arr) {
			for (int i : row)
				System.out.printf("%d ", i);
			System.out.println();
		}
	}

}
